/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logical.allhit.gui.action;

import com.logical.allhit.Kernel;
import com.logical.allhit.gui.MainFrom;
import com.logical.allhit.gui.model.AccountTableModel;
import com.logical.allhit.http.HTTPClient;
import com.logical.allhit.setting.Account;
import com.logical.allhit.setting.Setting;
import com.logical.allhit.util.AddAttribute;
import com.logical.allhit.util.MsgLogger;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author comp18
 */
public class Task extends SwingWorker<Boolean, Integer> {

    private boolean[] selection;
    private StartAction action;
    private MainFrom mainFrom;

    public Task(boolean[] selection, StartAction action, MainFrom mainFrom) {
        this.selection = selection;
        this.action = action;
        this.mainFrom = mainFrom;
    }

    @Override
    protected Boolean doInBackground() throws Exception {
        setProgress(0);
        String msg;
        AccountTableModel model = mainFrom.getAccountTableModel();

        for (int i = 0; i < model.getRowCount(); i++) {
            if ((Boolean) model.getValueAt(i, 0)) {
                Account account = model.getAccountAt(i);
                msg = "Select User " + account.getName();
                MsgLogger.getInstance().showMsg(msg);
                try {
                    if (HTTPClient.getInstance().login(account.getName(), account.getPassword(), account.getUsertype())) {
                    if (selection[0]) {//click Add
                        ArrayList<AddAttribute> urls = scanInbox(1);
//                    for (String url : urls) {
//                        clickAdd(url);
//                    }
                        int totalAddClick = 0;
                        for (int u = urls.size() - 1; u >= 0; u--) {
                            clickAdd(urls.get(u));
                            totalAddClick++;
                            try {
                                Thread.sleep(1000 * Setting.getInstance().getSleepTime());
                            } catch (Exception e) {
                                Logger.getLogger(Task.class.getName()).log(Level.WARNING, e.getMessage(), e);
                            }
                        }
                        msg = "Total Add clicked " + totalAddClick;
                        MsgLogger.getInstance().showMsg(msg);
                    }
                    if (selection[1]) {//Balance
//                        String balanceHtml = HTTPClient.getInstance().GET("http://202.87.47.29/~allhitde/pro_user/balanceinfo.php");
                        String balanceHtml = HTTPClient.getInstance().GET("http://"+Setting.getInstance().getHost()+"/pro_user/balanceinfo.php");
                        Document balanceDoc = Jsoup.parse(balanceHtml);
                        Element tr = balanceDoc.getElementsByTag("tr").last().getElementsByTag("td").last();
                        msg = "Balance for " + account.getName() + " are " + tr.text();
                        MsgLogger.getInstance().showMsg(msg);
                        account.setBalance(Float.parseFloat(tr.text()));
                        model.fireTableDataChanged();
                    }
                    if (selection[2]) {//User Tree
                        msg = "try to update user tree";
                        MsgLogger.getInstance().showMsg(msg);
                        String userTreeHtml = HTTPClient.getInstance().GET("http://"+Setting.getInstance().getHost()+"/pro_user/membertree.php?id="+ account.getUid());
                        Document userTreeDoc = Jsoup.parse(userTreeHtml);
                        Element td = userTreeDoc.getElementsByClass("table_cell").get(2);
                        String text = td.text();
                        //Left Users  : 4 Right Users : 3 Total Users : 7
                        long lu=0,ru=0,tu=0;
                        String lString = text.substring(text.indexOf("Left Pro Users  :")+17, text.indexOf("Right Pro Users")).trim();
                        if(lString.equals("")){
                            lString = "0";
                        }
                        lu = Long.parseLong(lString);
                        String rString = text.substring(text.indexOf("Right Pro Users :")+17, text.indexOf("Total Pro Users")).trim();
                        if(rString.equals("")){
                            rString = "0";
                        }
                        ru = Long.parseLong(rString);
                        String tString = text.substring(text.indexOf("Total Pro Users :")+17).trim();
                        if(tString.equals("0")){
                            tString = "0";
                        }
                        tu = Long.parseLong(tString);
                        account.setLeftchild(lu);
                        account.setRightchild(ru);
                        account.setTotalchild(tu);
                        model.fireTableDataChanged();
                        msg = "update user tree!";
                        MsgLogger.getInstance().showMsg(msg);
                    }
                    try {
                        Thread.sleep(1000 * Setting.getInstance().getSleepTime());
                        float curr = (float) i + 1;
                        int per = (int) ((curr / model.getRowCount()) * 100);
                        setProgress(per);
                    } catch (Exception e) {
                        Logger.getLogger(Task.class.getName()).log(Level.WARNING, e.getMessage(), e);
                    }
                    HTTPClient.getInstance().logout(account.getUsertype());
                    Runtime.getRuntime().gc();
                    System.gc();
                } else {
                    MsgLogger.getInstance().showMsg("Loging fild for " + account.getName() + " try agin ....");
                    break;
                }
                } catch (Exception e) {
                    Logger.getLogger(Task.class.getName()).log(Level.WARNING, e.getMessage(), e);
                }
                model.setValueAt(false, i, 0);
                model.fireTableDataChanged();
            }
        }
        msg = "End of process";
        setProgress(100);
        MsgLogger.getInstance().showMsg(msg);
        JOptionPane.showMessageDialog(Kernel.getInstance().getFrame(), msg);
        return true;
    }

    @Override
    protected void done() {
        super.done();
        action.setEnabled(true);
    }

    // url: http://www.allhitdeals.com/pro_user/inbox.php
    private ArrayList<AddAttribute> scanInbox(int pageNo) throws Exception{
        String msg = "Scaning Inbox page " + pageNo;
        boolean isfine = false;
        MsgLogger.getInstance().showMsg(msg);
        ArrayList<AddAttribute> urls = new ArrayList<AddAttribute>();
        String inbox = HTTPClient.getInstance().GET("http://"+Setting.getInstance().getHost()+"/pro_user/inbox.php?page=" + pageNo + "&");
        Document inboxDocument = Jsoup.parse(inbox);
        Element table = inboxDocument.getElementsByClass("box1").first();
        Elements imgs = table.getElementsByTag("img");
        Elements forms = table.getElementsByTag("form");
//        for (Element img : imgs) {
//            if (img.attr("src").equals("http://www.allhitdeals.com/pro_user/images/Pending.png")) {
//                isfine = true;
//                Element tr = img.parent().parent();
//                Element a = tr.child(1).child(0);
//                urls.add("http://www.allhitdeals.com/pro_user/" + a.attr("href"));
//            }
//        }
        for(int i = 0; i<imgs.size(); i++){
            Element img = imgs.get(i);
            if (img.attr("src").equals("http://www.allhitdeals.com/pro_user/images/Pending.png")) {
                isfine = true;
                AddAttribute addAttribute = new AddAttribute();
                Element form = forms.get(i);
                addAttribute.setAction("http://"+Setting.getInstance().getHost()+"/pro_user/" + form.attr("action"));
                Element tr = img.parent().parent();
                Element input = tr.child(1).child(1);
                addAttribute.setPostName(input.attr("name"));
                addAttribute.setPostValue(input.attr("value"));
                urls.add(addAttribute);
            }
        }
//        if (urls.size() == (pageNo * 22) && pageNo < 15) {
        if (isfine && pageNo < 15) {
            ArrayList<AddAttribute> urls1 = scanInbox(++pageNo);
            urls.addAll(urls1.subList(0, urls1.size()));
            pageNo--;
        }
        msg = "Scaning complet of page " + pageNo;
        MsgLogger.getInstance().showMsg(msg);
        return urls;
    }

    private void clickAdd(String url) throws Exception{
        String inbox = HTTPClient.getInstance().GET(url);
        Document inboxDocument = Jsoup.parse(inbox);
        Element table = inboxDocument.getElementsByClass("formbg").first();
        Element a = table.getElementsByTag("img").first().parent();
        String msg = "cilck add on " + a.attr("href");
        String script = HTTPClient.getInstance().GET("http://"+Setting.getInstance().getHost()+"/pro_user/" + a.attr("href"));
        MsgLogger.getInstance().showMsg(msg);
//        HTTPClient.getInstance().GET(script.substring(script.indexOf("document.location.href='") + "document.location.href='".length(), script.indexOf("'</script>")));
//        msg = "go other server";
//        MsgLogger.getInstance().showMsg(msg);
    }
    
    private void clickAdd(AddAttribute attribute)throws Exception{
        String mail = HTTPClient.getInstance().loadmail(attribute);
        Document inboxDocument = Jsoup.parse(mail);
        Element table = inboxDocument.getElementsByClass("formbg").first();
        Element a = table.getElementsByTag("img").first().parent();
        String msg = "cilck add on " + a.attr("href");
        String script = HTTPClient.getInstance().GET("http://"+Setting.getInstance().getHost()+"/pro_user/" + a.attr("href"));
        MsgLogger.getInstance().showMsg(msg);
    }
}
